﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using OSGeo.MapGuide;
using System.Xml;
using Jayrock;
using Jayrock.Json;
using Jayrock.Collections;
using System.Collections.Specialized;
namespace IGIS
{
    public partial class printablepage : utilityfunctions
    {

      public  String mapName = "";
      public String TitleName = "";
      public String sessionId = "";
      public String locale = "";
      public int isTitle = 0;
      public int isLegend = 0;
      public int isMinimap = 0; //Added for minimap script
      public int isArrow = 0;
      public int isLogo = 0;
      public String title = "";
      public String scale = "";
      public String centerX = "";
      public String centerY = "";
      public String dpi = "";
      public int isFrame = 0;
      public String netType = "";
      public int prSize = 0;
      public String prScale = "";
      public String prOrientation = "";
      public String prLegend = "";
      public String hideLayer = "";       //Added for minimap script
      public String MinimapImageUrl = ""; //Added for minimap script

      public string getGetLegendInfo = string.Empty;
      public common _comm = new common();

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Charset = "utf-8";

            try
            {

               
                //fetch the parameters for this request
                //
                GetRequestParameters();
                getGetLegendInfo = GetLegendInfo();
                MgLocalizer.SetLocalizedFilesPath(Request.ServerVariables["APPL_PHYSICAL_PATH"] + "..\\localized\\");
              /*  String templ = MgLocalizer.Localize(LoadTemplate(Request, "../viewerfiles/Add-On/printablepage.templ"), locale, GetClientOS(Request));
                String agent = GetRootVirtualFolder(Request) + "/mapagent/mapagent.fcgi";
                String[] vals = {
            mapName,
            MinimapImageUrl,
            agent,
            scale,
            centerX,
            centerY,
            dpi,
            mapName,
            sessionId,
			hideLayer, //Added for minimap script
            isTitle.ToString(NumberFormatInfo.InvariantInfo),
            isLegend.ToString(NumberFormatInfo.InvariantInfo),
            isMinimap.ToString(NumberFormatInfo.InvariantInfo),
            isArrow.ToString(NumberFormatInfo.InvariantInfo),
            isLogo.ToString(NumberFormatInfo.InvariantInfo),
            isFrame.ToString(NumberFormatInfo.InvariantInfo),
            isFrame == 1 ? netType : "",
            prSize.ToString(NumberFormatInfo.InvariantInfo),
            prScale,
            prOrientation,
            GetLegendInfo(),
            Session["LOGO"].ToString(),
            isTitle == 1 ? title : "",
            TitleName,
            mapName,
            sessionId,
            TitleName};

                Response.Write(Substitute(templ, vals));*/

                tester();
            }
            catch (Exception ne)
            {
                Response.Write(ne.Message);
            }
        }

        private void tester()
        {
          



        }
        string GetLegendInfo()
        {
            MgSiteConnection conn = new MgSiteConnection();
            conn.Open(new MgUserInformation(sessionId));

            MgResourceService resourceService = conn.CreateService(MgServiceType.ResourceService) as MgResourceService;

            MgMap map = new MgMap();
            map.Open(resourceService, mapName);
          
            List<LayerLegendInfo> infos = new List<LayerLegendInfo>();

            foreach (MgLayer layer in map.GetLayers())
            {
                if (layer.DisplayInLegend && layer.IsVisible() && !String.IsNullOrEmpty(layer.Name) && layer.LegendLabel != "MapOverview")
                {
                    LayerLegendInfo layerInfo = GetLayerContent(resourceService, layer, Convert.ToDouble(scale));
                    if (layerInfo != null)
                        infos.Add(layerInfo);
                }
            }

            System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
         new System.Web.Script.Serialization.JavaScriptSerializer();
            string sJSON = oSerializer.Serialize(infos);
            return sJSON;
            //return string.Empty;
        }
        LayerLegendInfo GetLayerContent(MgResourceService resourceService, MgLayer layer, double scale)
        {
            bool insertInToList = false;

            string[] styleTypes = new[] { "PointTypeStyle", "LineTypeStyle", "AreaTypeStyle", "CompositeTypeStyle" };
            string[] ruleNames = new[] { "PointRule", "LineRule", "AreaRule", "CompositeRule" };

            LayerLegendInfo layerInfo = new LayerLegendInfo { Name = layer.Name, Label = layer.LegendLabel, Path = layer.LayerDefinition.ToString() };

            string xmlContent = resourceService.GetResourceContent(layer.LayerDefinition).ToString();

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlContent);

            XmlNodeList scaleNodes = doc.GetElementsByTagName("VectorScaleRange");
            foreach (XmlElement scaleRange in scaleNodes)
            {
                double minScale = 0.0;
                double maxScale = 1000000000000.0;

                XmlNode minScaleNode = scaleRange.SelectSingleNode("MinScale");
                XmlNode maxScaleNode = scaleRange.SelectSingleNode("MaxScale");
                if (minScaleNode != null) minScale =Convert.ToDouble(minScaleNode.InnerText);
                if (maxScaleNode != null) maxScale = Convert.ToDouble(maxScaleNode.InnerText);
                if (scale > minScale && scale < maxScale)
                {

                    for (int stylesIndex = 0; stylesIndex < styleTypes.Length; stylesIndex++)
                    {
                        foreach (XmlElement element in (scaleRange).GetElementsByTagName(styleTypes[stylesIndex]))
                        {
                            int legendIndex = -1;
                            foreach (XmlElement rule in element.GetElementsByTagName(ruleNames[stylesIndex]))
                            {
                                string legendLabel = rule.SelectSingleNode("LegendLabel").InnerText;
                                if (string.IsNullOrEmpty(legendLabel)) continue;
                                LayerLegendInfo info = new LayerLegendInfo { Label = HttpUtility.HtmlAttributeEncode(legendLabel), Path = layerInfo.Path, GeomType = stylesIndex + 1, LegendIndex = ++legendIndex };
                                layerInfo.Children.Add(info);
                            }
                            insertInToList = true;
                        }
                    }
                    break;
                }
            }
            return insertInToList ? layerInfo : null;
            //return layerInfo;
        }

        void GetRequestParameters()
        {
            if ("POST" == Request.HttpMethod)
            {
                GetParameters(Request.Form);
            }
            else
            {
                GetParameters(Request.QueryString);
            }
        }

        void GetParameters(NameValueCollection parameters)
        {
            locale = GetParameter(parameters, "LOCALE");
            if (_comm.IsParameter(parameters, "MAPNAME"))
            {
                mapName = GetParameter(parameters, "MAPNAME");
            }
            if (_comm.IsParameter(parameters, "SESSION"))
            {
                sessionId = GetParameter(parameters, "SESSION");
            }
            if (_comm.IsParameter(parameters, "ISTITLE"))
            {
                isTitle = Convert.ToInt32(GetParameter(parameters, "ISTITLE"));
            }
            if (_comm.IsParameter(parameters, "ISLEGEND"))
            {
                isLegend = Convert.ToInt32(GetParameter(parameters, "ISLEGEND"));
            }
            if ( _comm.IsParameter(parameters, "ISARROW"))
            {
                isArrow = Convert.ToInt32(GetParameter(parameters, "ISARROW"));
            }
            if ( _comm.IsParameter(parameters, "TITLE"))
            {
                title = GetParameter(parameters, "TITLE");
            }
            if ( _comm.IsParameter(parameters, "TITLE_NAME"))
            {
                TitleName = GetParameter(parameters, "TITLE_NAME");
            }
            if ( _comm.IsParameter(parameters, "SCALE"))
            {
                scale = GetParameter(parameters, "SCALE");
            }
            if ( _comm.IsParameter(parameters, "CENTERX"))
            {
                centerX = GetParameter(parameters, "CENTERX");
            }
            if ( _comm.IsParameter(parameters, "CENTERY"))
            {
                centerY = GetParameter(parameters, "CENTERY");
            }
            if ( _comm.IsParameter(parameters, "DPI"))
            {
                dpi = GetParameter(parameters, "DPI");
            }
            if ( _comm.IsParameter(parameters, "ISFRAME"))
            {
                isFrame = Convert.ToInt32(GetParameter(parameters, "ISFRAME"));
            }
            if ( _comm.IsParameter(parameters, "NETTYPE"))
            {
                netType = GetParameter(parameters, "NETTYPE");
            }
            if ( _comm.IsParameter(parameters, "PAPERSIZE"))
            {
                prSize = Convert.ToInt32(GetParameter(parameters, "PAPERSIZE"));
            }
            if ( _comm.IsParameter(parameters, "PAPERSCALE"))
            {
                prScale = GetParameter(parameters, "PAPERSCALE");
            }
            if ( _comm.IsParameter(parameters, "PAPERORIENTATION"))
            {
                prOrientation = GetParameter(parameters, "PAPERORIENTATION");
            }
            if ( _comm.IsParameter(parameters, "LEGEND"))
            {
                prLegend = GetParameter(parameters, "LEGEND");
            }
            // Begin of Minimap add-in =========================================================================
            if ( _comm.IsParameter(parameters, "HIDELAYER"))
            {
                hideLayer = GetParameter(parameters, "HIDELAYER");
            }
            if ( _comm.IsParameter(parameters, "MINIMAPIMAGEURL"))
            {
                MinimapImageUrl = GetParameter(parameters, "MINIMAPIMAGEURL");
            }
            if ( _comm.IsParameter(parameters, "ISMINIMAP"))
            {
                isMinimap = Convert.ToInt32(GetParameter(parameters, "ISMINIMAP"));
            }
            // End of Minimap add-in ===========================================================================
            // Begin of Logo add-in =========================================================================
            if ( _comm.IsParameter(parameters, "ISLOGO"))
            {
                isLogo = Convert.ToInt32(GetParameter(parameters, "ISLOGO"));
            }
            // End of Logo add-in ===========================================================================
        }




    }

    public class LayerLegendInfo
    {
        public string Name { get; set; }
        public string Label { get; set; }
        public string Path { get; set; }

        public int GeomType { get; set; }
        public int LegendIndex { get; set; }

        public List<LayerLegendInfo> Children { get; set; }

        public LayerLegendInfo()
        {
            Children = new List<LayerLegendInfo>();
        }
    }
}